//Cracking the coding interview (5ed), 2_2
//Implement an algorithm to find the kth to last element of a singly linked list.
//3:36pm-4:36pm
//author:Fan Yang

#include <stdio.h>
#include <stdlib.h>

struct ListElem
{
	int data;
	struct ListElem * next;
};

struct ListElem * InitList(int length)
{
	struct ListElem * head,*p1,*p2;
	head=(struct ListElem *)malloc(sizeof(struct ListElem));
	head->data=1;
	head->next=NULL;
	p1=head;
	p2=head;
	for(int i=1;i<length;i++)
	{
		p1=(struct ListElem *)malloc(sizeof(struct ListElem));
		p1->data=i+1;
		p1->next=NULL;
		p2->next=p1;
		p2=p1;
	}
	return head;
}

int main()
{
	int L,K,count=1;
	struct ListElem * pt1,* pt2,* list_head;
	printf("Input the length of the list and the value of K: ");
	scanf("%d %d",&L,&K);
	list_head=InitList(L);
	pt1=list_head;
	pt2=list_head;
	while(pt1->next!=NULL)
	{
		pt1=pt1->next;
		count++;
		if(count>K)
		{
			pt2=pt2->next;
		}
	}
	printf("%d",pt2->data);
	return 1;
}
